<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目详情</title>
    <script src="common.js"></script>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden; /* Prevent body scrollbar */
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f7f6;
            color: #333;
        }

        .modal-content {
            background-color: #fefefe;
            margin: 0; /* Remove margin */
            padding: 10px; /* Keep some padding */
            border: none; /* Remove border */
            border-radius: 0; /* Remove border-radius */
            position: absolute; /* Use absolute positioning */
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            box-shadow: none; /* Remove box-shadow */
            overflow: auto; /* Add scroll if content overflows */
        }

        .detail-actions button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }

        .detail-actions button:hover {
            background-color: #0056b3;
        }

        .detail-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        .detail-table td {
            border: 1px solid #ddd;
            padding: 8px;
            vertical-align: top; /* Align content to top */
            height: 1px; /* Set a minimal height to allow content to define row height */
            white-space: normal; /* Allow text to wrap */
            overflow: auto; /* Enable scrollbars if content overflows */
            resize: vertical; /* Allow vertical resizing */
            background-color: inherit;
        }

        .detail-table th {
            background-color: #f2f2f2;
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
            vertical-align: center;
            overflow: auto; /* Enable scrollbars if content overflows */
            resize: horizontal; /* Allow horizontal resizing */
        }

        .detail-table tr {
            height: auto; /* Allow row height to adjust based on content */
            resize: vertical;
        }

        .detail-table tbody tr:nth-child(odd) {
            background-color: #f2ece8;
        }

        .detail-table tbody tr:nth-child(even) {
            background-color: #ffffff;
        }

        .detail-table .detail-textarea {
            min-height: 60px;
            border: 1px solid #ccc;
            padding: 5px;
            box-sizing: border-box;
            font-family: inherit;
            font-size: inherit;
            width: 100%;
            height: 100%; /* Make textarea fill the height of its parent td */
            background-color: inherit;
        }

        .detail-table audio {
            width: 100%;
            min-width: 100px;
        }

        .detail-table button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 3px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 10px;
            margin-bottom: 5px;
            margin-right: 5px;
            display: inline-block;
        }

        .detail-table button.regenerate-btn {
            background-color: #28a745; /* Green for regenerate buttons */
        }
        
        .detail-table button.edit-btn {
            background-color: #28a745; /* Green for regenerate buttons */
        }

        .detail-table button:hover {
            background-color: #c82333;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .modal-content {
                width: 95%;
                padding: 15px;
            }

            .detail-actions button {
                width: 100%;
            }

            .detail-table th,
            .detail-table td {
                padding: 6px;
                font-size: 12px;
            }


        }

        .role-tag {
            display: inline-flex;
            align-items: center;
            background-color: #e0e0e0;
            border-radius: 3px;
            padding: 2px 5px;
            margin: 2px;
            font-size: 12px;
        }

        .role-tag-close {
            margin-left: 5px;
            cursor: pointer;
            font-weight: bold;
            color: #888;
        }

        .role-tag-close:hover {
            color: #333;
        }
    </style>
    <style>
        /* Modal styles */
        .modal {
            display: none; /* Hidden by default */
            position: fixed; /* Stay in place */
            z-index: 1001; /* Sit on top */
            padding-top: 60px; /* Location of the box */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%; /* Full height */
            overflow: auto; /* Enable scroll if needed */
            background-color: rgb(0,0,0); /* Fallback color */
            background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
        }

        /* Modal Content (image) */
        .modal-content-image {
            margin: auto;
            display: block;
            width: 80%;
            max-width: 700px;
        }

        /* Caption of Modal Image */
        #caption {
            margin: auto;
            display: block;
            width: 80%;
            max-width: 700px;
            text-align: center;
            color: #ccc;
            padding: 10px 0;
            height: 150px;
        }

        /* Add Animation - Zoom in the Modal */
        .modal-content-image, #caption {
            animation-name: zoom;
            animation-duration: 0.6s;
        }

        @keyframes zoom {
            from {transform:scale(0)}
            to {transform:scale(1)}
        }

        /* The Close Button */
        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            transition: 0.3s;
        }

        .close:hover,
        .close:focus {
            color: #bbb;
            text-decoration: none;
            cursor: pointer;
        }

        /* 100% Image Width on Smaller Screens */
        @media only screen and (max-width: 700px){
            .modal-content-image {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div id="message-area"></div>
    <div class="modal-content">
        <div class="detail-actions">
            <button>一键完成 (prompt, 配音, 配图, 草稿)</button>
            <button>生成场景描述</button>
            <button>生成prompt</button>
            <button>生成配音</button>
            <button>生成配图</button>
            
            <button>comfyUI配图</button>
            <button>comfyUI配音</button>
            <button>生成草稿</button>
            <button id="reconnectWsBtn">重新连接 WebSocket</button>
        </div>
        <button id="mountRoleBtn" class="btn btn-primary">挂载角色</button>
            <!-- 角色列表模态框 -->
            <div id="roleListModal" class="modal" style="display: none;">
                <div class="modal-content" style="width: 80%; max-width: 800px;">
                    <div class="modal-header">
                        <h2>选择角色</h2>
                        <span class="close">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div id="roleList" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; padding: 20px;">
                            <!-- 角色卡片将通过 JavaScript 动态添加 -->
                        </div>
                    </div>
                </div>
            </div>
        <div id="roleTab">
            
        </div>
        <style>
            .modal {
                display: none;
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.4);
            }
           
            .close {
                color: #aaa;
                float: right;
                font-size: 28px;
                font-weight: bold;
                cursor: pointer;
            }
            .close:hover {
                color: black;
            }
            .role-card {
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 10px;
                text-align: center;
                cursor: pointer;
                transition: transform 0.2s;
            }
            .role-card:hover {
                transform: translateY(-5px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
            .role-card img {
                width: 100px;
                height: 100px;
                object-fit: cover;
                border-radius: 50%;
                margin-bottom: 10px;
            }
            .role-card.selected {
                border: 2px solid #007bff;
                background-color: #f8f9fa;
            }
            .selected {
                border: 1px solid #123123
            }
        </style>
        <script>
            
        </script>
        <div class="table-container" style="overflow: auto; height: 100%;">
            <table class="detail-table">
                <thead>
                <tr>
                    <th style="width: 30px;"><input type="checkbox" id="select-all-checkbox"></th>
                    <th>ID</th>
                    <th style="max-width: 220px;">段落内容</th>
                    <th style="max-width: 80px;">角色</th>
                    <th style="max-width: 220px;">分词结果</th>
                    <th style="max-width: 220px;">提示词prompt</th>
                    <th>配音</th>
                    <th>配图</th>
                </tr>
            </thead>
            <tbody>
               
            </tbody>
        </table>
    </div>
    <script>
        // WebSocket 连接
        let ws;
        let reconnectInterval;

        function connectWebSocket() {
            ws = getWebSocket()

            ws.onopen = function(event) {
                console.log('WebSocket 连接成功');
                showMessage('WebSocket 连接成功', 'success');
                if (reconnectInterval) {
                    clearInterval(reconnectInterval);
                    reconnectInterval = null;
                }
                document.getElementById("reconnectWsBtn").style.display = "none";
            };

            ws.onmessage = function(event) {
                console.log('收到 WebSocket 消息:', event.data);
                const message = JSON.parse(event.data);
                if (message.code === 1 && message.data) {
                    const data = message.data;
                    if (data.audio_path && data.id) {
                        const audioPlayer = document.getElementById(`audio-player-${data.id}`);
                        if (audioPlayer) {
                            audioPlayer.src = data.audio_path;
                        } else {
                            const newAudioPlayer = document.createElement('audio');
                            newAudioPlayer.id = `audio-player-${data.id}`;
                            newAudioPlayer.controls = true;
                            newAudioPlayer.src = data.audio_path;
                            const audioContainer = document.getElementById(`audio-container-${data.id}`);
                            if (audioContainer) {
                                audioContainer.innerHTML = newAudioPlayer.outerHTML;
                            }
                        }
                    }else if (data.image_path && data.id) {
                        const imageElement = document.getElementById(`image-${data.id}`);
                        const imageElement1 = document.getElementById(`image-comfyui-${data.id}`);
                        if (imageElement) {
                            imageElement.src = data.image_path;
                            imageElement1.value = data.image_comfyui;
                        } else {
                            const newImagePlayer = document.createElement('img');
                            newImagePlayer.id = `image-${data.id}`;
                            newImagePlayer.src = data.image_path;
                            newImagePlayer.style.maxWidth = '100px';
                            newImagePlayer.style.maxHeight = '100px';
                            const imageContainer = document.getElementById(`image-container-${data.id}`);
                            if (imageContainer) {
                                imageContainer.innerHTML = newImagePlayer.outerHTML;
                            }
                        }
                    }else if(data.prompt_data && data.id) {
                        const textareaElement = document.getElementById(`prompt-${data.id}`);
                        if (textareaElement) {
                            textareaElement.value = data.prompt_data;
                        }
                    }else if (data.split_data && data.id) {
                        let textareaElement = document.getElementById(`split-${data.id}`);
                        if (textareaElement) {
                            textareaElement.value = data.split_data;
                        }
                        textareaElement = document.getElementById(`prompt-${data.id}`);
                        if (textareaElement) {
                            textareaElement.value = data.prompt;
                        }
                    }
                    if (message.msg) {
                        showMessage(message.msg, 'success');
                    }
                } else if (message.code === 1) {
                    showMessage(message.msg, 'success');
                } else if (message.code === -1) {
                    showMessage(message.msg, 'error');
                } else if (message.code === 0) {
                    showMessage(message.msg, 'gray');
                } else if (message.msg) {
                    showMessage(message.msg, 'gray');
                }
            };

            ws.onerror = function(error) {
                console.error('WebSocket 错误:', error);
                showMessage('WebSocket 连接错误，请尝试重新连接', 'error');
                document.getElementById("reconnectWsBtn").style.display = "block";
            };

            ws.onclose = function(event) {
                console.log('WebSocket 连接关闭:', event.code, event.reason);
                showMessage('WebSocket 连接已关闭，正在尝试重新连接...', 'gray');
                if (!reconnectInterval) {
                    reconnectInterval = setInterval(connectWebSocket, 5000); // 每5秒尝试重连
                }

            };
        }

        // 初始连接
        connectWebSocket();

        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const projectId = urlParams.get('projectId');

            // Reconnect button event listener
            document.getElementById('reconnectWsBtn').addEventListener('click', function() {
                console.log('尝试重新连接 WebSocket...');
                showMessage('正在尝试重新连接 WebSocket...', 'gray');
                if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
                    ws.close(); // Close existing connection if open or connecting
                }
                document.getElementById("reconnectWsBtn").style.display = "block";
                connectWebSocket();
            });

            if (projectId) {
                fetch(`/project/query?project_id=${projectId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 0) {
                            const tbody = document.querySelector('.detail-table tbody');
                            tbody.innerHTML = ''; // Clear existing rows
                        data.data.forEach(item => {
                            const row = `
                                <tr>
                                    <td><input style="text-align: center;" type="checkbox" class="row-checkbox" data-id="${item.id}"></td>
                                    <td style="text-align: center;">${item.id}</td>
                                    <td>
                                        <textarea class="detail-textarea" readonly>${item.content}</textarea>
                                    </td>
                                     <td>
                                        <button class="edit-btn" data-type="role_ids" data-id="${item.id}">修改保存</button>
                                        <br>
                                        <input id="role_ids-${item.id}" type="hidden" value ="${item.role_ids || ''}"/>
                                        <div id="role_names_display-${item.id}" style="width: 100%; height: 100%; box-sizing: border-box; padding: 0; margin: 0;" ondragover="event.preventDefault();" ondrop="handleDrop(event, '${item.id}')"></div>
                                        
                                        <input type="hidden" id="role_names-${item.id}" value="${item.role_names || ''}">
                                    </td>
                                    <td>
                                        <button class="edit-btn" data-type="split" data-id="${item.id}">修改保存</button>
                                        <button class="regenerate-btn" data-type="split" data-id="${item.id}">重新生成</button>
                                        <br>
                                        <textarea id="split-${item.id}" class="detail-textarea" >${item.split || ''}</textarea>
                                    </td>
                                    <td>
                                        <button class="edit-btn" data-type="prompt" data-id="${item.id}">修改保存</button>
                                        <button class="regenerate-btn" data-type="prompt" data-id="${item.id}">重新生成</button>
                                        <br>
                                        <textarea id="prompt-${item.id}" class="detail-textarea" >${item.prompt || ''}</textarea>
                                    </td>
                                    <td>
                                        <button class="regenerate-btn" data-type="audio" data-id="${item.id}">重新生成</button>
                                        <br>
                                        ${item.audio ? `<audio id="audio-player-${item.id}" controls src="${item.audio}"></audio>` : `<div id="audio-container-${item.id}">无</div>`}
                                    </td>
                                    <td>
                                        <button class="regenerate-btn" data-type="image" data-id="${item.id}">重新生成</button>
                                        <button class="regenerate-btn" data-type="imageUp" data-id="${item.id}">微调图片</button>
                                        <br>
                                        ${item.image ? `<img id="image-${item.id}" src="${item.image}" alt="AI Image" style="max-width: 100px; max-height: 100px;">` : `<div id="image-container-${item.id}">无</div>`}
                                        ${item.image_comfyui ? `<input type="hidden" id="image_comfyui-${item.id}" value="${item.image_comfyui}" >` : `<input type="hidden" id="image_comfyui-${item.id}" value="" >`}
                                        
                                    </td>
                                </tr>
                            `;
                            tbody.innerHTML += row;
                            displayRoleTags(item.id)
                        });

                        // Add event listeners for buttons
                        tbody.addEventListener('click', function(event) {
                            if (event.target.tagName === 'BUTTON') {
                                const button = event.target;
                                const id = button.dataset.id;
                                const type = button.dataset.type;

                                if (button.classList.contains('regenerate-btn')) {
                                    console.log(`Regenerate button clicked: ID = ${id}, Type = ${type}, ProjectID = ${projectId}`);
                                    if(type == 'image'){
                                        //询问是否使用cumfyui
                                        if(confirm('是否使用cumfyui生成图片？')){
                                            ws.send(JSON.stringify({ action: 'regenerate-by-comfyui-'+type, data:{id: id, project_id: projectId }}));
                                        }else{
                                            ws.send(JSON.stringify({ action: 'regenerate-'+type, data:{id: id, project_id: projectId }}));
                                        }
                                    } else if(type == 'audio'){
                                        //询问是否使用cumfyui
                                        if(confirm('是否使用cumfyui生成音频？')){
                                            ws.send(JSON.stringify({ action: 'regenerate-by-comfyui-'+type, data:{id: id, project_id: projectId }}));
                                        }else{
                                            ws.send(JSON.stringify({ action: 'regenerate-'+type, data:{id: id, project_id: projectId }}));
                                        }
                                    } else if(type == 'imageUp'){
                                            //弹框输入提示词
                                            const prompt = window.prompt('请输入提示词：', '');
                                        if(prompt && prompt.trim() !== ''){
                                            const image_comfyui = document.getElementById("image_comfyui-"+id).value;
                                            
                                            ws.send(JSON.stringify({ action: 'regenerate-by-comfyui-kontext-'+type, data:{id: id, project_id: projectId, prompt: prompt, imgPath: image_comfyui }}));
                                        }
                                    }else{
                                        ws.send(JSON.stringify({ action: 'regenerate-'+type, data:{id: id, project_id: projectId }}));
                                    }
                                    
                                } else if (button.classList.contains('edit-btn')) {
                                    console.log(`edit button clicked: ID = ${id}, Type = ${type}`);
                                    ws.send(JSON.stringify({ action: 'update-'+type, data:{id: id, project_id: projectId, data: document.getElementById(type+"-"+id).value }}));
                                   
                                } else {
                                    console.log(`Other button clicked: ID = ${id}, Type = ${type}`);
                                    // Handle other buttons if necessary
                                }
                            } else if (event.target.tagName === 'SPAN') {
                                const button = event.target;
                                const id = button.dataset.id;
                                if (button.classList.contains('role-tag-close')) {
                                    console.log(`Regenerate button clicked: ID = ${id}, ProjectID = ${projectId}`);
                                    removeRoleTag(id, button.dataset.roleId,button.dataset.roleName);
                                }
                            } else if (event.target.tagName === 'IMG') {
                                const img = event.target;
                                if (img.closest('.detail-table')) { // Ensure the image is within the detail table
                                    modal.style.display = "block";
                                    modalImg.src = img.src;
                                }
                            }
                        });

                        // Add event listeners for top action buttons
                        document.querySelector('.detail-actions').addEventListener('click', function(event) {
                            if (event.target.tagName === 'BUTTON') {
                                const buttonText = event.target.textContent.trim();
                                console.log(`Top action button clicked: ${buttonText}`);
                                // Implement logic for top action buttons
                                switch(buttonText) {
                                    case '一键完成 (prompt, 配音, 配图, 草稿)':
                                        ws.send(JSON.stringify({ action: 'regenerate_all', data: { project_id: projectId } }));
                                        break;
                                    case '生成场景描述':
                                        ws.send(JSON.stringify({ action: 'generate_scene', data: { project_id: projectId } }));
                                        break;
                                    case '生成prompt':
                                        ws.send(JSON.stringify({ action: 'generate_prompt', data: { project_id: projectId } }));
                                        break;
                                    case '生成配音':
                                        ws.send(JSON.stringify({ action: 'generate_audio', data: { project_id: projectId } }));
                                        break;
                                    case '生成配图':
                                        ws.send(JSON.stringify({ action: 'generate_image', data: { project_id: projectId } }));
                                        break;
                                    case 'comfyUI配图':
                                        ws.send(JSON.stringify({ action: 'generate_image_by_comfyui', data: { project_id: projectId } }));
                                        break;
                                    case 'comfyUI配音':
                                        ws.send(JSON.stringify({ action: 'generate_audio_by_comfyui', data: { project_id: projectId } }));
                                        break;
                                    case '生成草稿':
                                        ws.send(JSON.stringify({ action: 'generate_draft', data: { project_id: projectId } }));
                                        break;
                                }
                            }
                        });

                    } else {
                        console.error('Failed to fetch project details:', data.message);
                    }
                })
                .catch(error => {
                    console.error('Error fetching project details:', error);
                });
                // 通过WXprojectid查询项目角色
                fetch(`/project/queryRoles?project_id=${projectId}`)
                   .then(response => response.json())
                   .then(data => {
                        if (data.code === 1) {
                            // 渲染角色标签
                            const roleTab = document.getElementById('roleTab');
                            roleTab.innerHTML = '';
                            // 尝试从 data.data[0].roles 或 data.data[0].users 获取角色
                            if (!!data.data && data.data.length > 0) {
                                // 渲染角色标签，显示id和name
                                data.data.forEach(role => {
                                    const tag = document.createElement('span');
                                    tag.dataId = role.id;
                                    tag.textContent = role.name;
                                    tag.draggable = true; // Make the tag draggable
                                    tag.classList.add('draggable-role'); // Add a class for easier selection
                                    tag.style.display = 'inline-block';
                                    tag.style.background = '#e0e7ff';
                                    tag.style.color = '#333';
                                    tag.style.borderRadius = '12px';
                                    tag.style.padding = '4px 12px';
                                    tag.style.margin = '4px 8px 4px 0';
                                    tag.style.fontSize = '14px';
                                    tag.style.border = '1px solid #b3b3b3';
                                    roleTab.appendChild(tag);
                                    tag.addEventListener('dblclick', (e) => {
                                        editRole(role.id);
                                    });
                                    tag.addEventListener('dragstart', (e) => {
                                        e.dataTransfer.setData('text/plain', JSON.stringify({ id: role.id, name: role.name }));
                                    });
                                });
                            } else {
                                roleTab.innerHTML = '<span style="color: #888;">暂无角色信息</span>';
                            }
                            
                        } else {
                            console.error('Failed to fetch ROLE details:', data.message);
                    }
                })
                .catch(error => {
                    console.error('Error fetching ROLE details:', error);
                });
            }
            // 获取模态框元素
            const roleListModal = document.getElementById('roleListModal');
            const closeBtn = roleListModal.querySelector('.close');
            const mountRoleBtn = document.getElementById('mountRoleBtn');
            const roleList = document.getElementById('roleList');
            let selectedRoles = new Set();

            // 打开模态框并加载角色列表
            mountRoleBtn.onclick = function() {
                roleListModal.style.display = 'block';
                loadRoleList();
            }

            // 关闭模态框
            closeBtn.onclick = function() {
                roleListModal.style.display = 'none';
            }

            // 点击模态框外部关闭
            window.onclick = function(event) {
                if (event.target == roleListModal) {
                    roleListModal.style.display = 'none';
                }
            }

            // 加载角色列表
            function loadRoleList() {
                fetch(`/role/queryAll?project_id=${projectId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 0) {
                            roleList.innerHTML = '';
                            data.data.forEach(role => {
                                const card = document.createElement('div');
                                card.className = 'role-card';
                                if(role.selected!=""){
                                    card.classList.add('selected');
                                }
                                card.innerHTML = `
                                    <img src="${role.imgPath || '/public/personImgs/user.jpg'}" alt="${role.name}">
                                    <h3>${role.name}</h3>
                                `;
                                card.onclick = function() {
                                    const checkboxes = document.querySelectorAll('.row-checkbox:checked');
                                    if (checkboxes.length === 0) {
                                        showMessage('请先选择要挂载角色的段落', 'error');
                                        return;
                                    }
                                    
                                    checkboxes.forEach(checkbox => {
                                        const id = checkbox.dataset.id;
                                        const roleIdsInput = document.getElementById(`role_ids-${id}`);
                                        const roleNamesInput = document.getElementById(`role_names-${id}`);
                                        
                                        let roleIds = roleIdsInput.value ? roleIdsInput.value.split(',') : [];
                                        let roleNames = roleNamesInput.value ? roleNamesInput.value.split(',') : [];
                                        
                                        if (!roleIds.includes(role.id)) {
                                            roleIds.push(role.id);
                                            roleNames.push(role.name);
                                            
                                            roleIdsInput.value = roleIds.join(',');
                                            roleNamesInput.value = roleNames.join(',');
                                            
                                            // 触发保存
                                            const saveBtn = document.querySelector(`button[data-type="role_ids"][data-id="${id}"]`);
                                            if (saveBtn) {
                                                saveBtn.click();
                                            }
                                            
                                            // 更新显示
                                            displayRoleTags(id);
                                        }
                                    });
                                    
                                    roleListModal.style.display = 'none';
                                    showMessage('角色挂载成功', 'success');
                                };
                                roleList.appendChild(card);
                            });
                        } else {
                            showMessage('加载角色列表失败', 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error loading roles:', error);
                        showMessage('加载角色列表失败', 'error');
                    });
            }
        });
        
        function handleDrop(event, itemId) {
            event.preventDefault();
            const data = JSON.parse(event.dataTransfer.getData('text/plain'));
            const roleId = data.id;
            const roleName = data.name;

            const roleIdsInput = document.getElementById(`role_ids-${itemId}`);
            const roleNamesInput = document.getElementById(`role_names-${itemId}`);

            // Append role ID
            if (roleIdsInput.value) {
                const currentIds = roleIdsInput.value.split(',').map(id => id.trim());
                if (!currentIds.includes(roleId.toString())) {
                    roleIdsInput.value += `,${roleId}`;
                }
            } else {
                roleIdsInput.value = roleId;
            }

            // Append role Name
            if (roleNamesInput.value) {
                const currentNames = roleNamesInput.value.split(',').map(name => name.trim());
                if (!currentNames.includes(roleName)) {
                    roleNamesInput.value += `,${roleName}`;
                }
            } else {
                roleNamesInput.value = roleName;
            }
            displayRoleTags(itemId);
        }

        function displayRoleTags(itemId) {
            const roleNamesInput = document.getElementById(`role_names-${itemId}`);
            const roleIdsInput = document.getElementById(`role_ids-${itemId}`);
            const roleNamesDisplay = document.getElementById(`role_names_display-${itemId}`);

            roleNamesDisplay.innerHTML = ''; // Clear existing tags

            if (roleNamesInput.value) {
                const roleNames = roleNamesInput.value.split(',');
                const roleIds = roleIdsInput.value.split(',');

                roleNames.forEach((name, index) => {
                    const tag = document.createElement('span');
                    tag.classList.add('role-tag');
                    tag.textContent = name.trim();
                    tag.dataset.id = roleIds[index].trim(); // Store role ID in dataset

                    const closeBtn = document.createElement('span');
                    closeBtn.classList.add('role-tag-close');
                    closeBtn.textContent = '×';
                    

                    tag.appendChild(closeBtn);
                    roleNamesDisplay.appendChild(tag);
                    closeBtn.dataset.id = itemId;
                    closeBtn.dataset.roleId = roleIds[index].trim();
                    closeBtn.dataset.roleName = name;
                });
            }
        }

        function removeRoleTag(itemId, roleIdToRemove, roleNameToRemove) {
            const roleIdsInput = document.getElementById(`role_ids-${itemId}`);
            const roleNamesInput = document.getElementById(`role_names-${itemId}`);

            let currentIds = roleIdsInput.value.split(',').map(id => id.trim());
            let currentNames = roleNamesInput.value.split(',').map(name => name.trim());

            const indexToRemove = currentIds.findIndex((id, index) => id === roleIdToRemove && currentNames[index] === roleNameToRemove);

            if (indexToRemove > -1) {
                currentIds.splice(indexToRemove, 1);
                currentNames.splice(indexToRemove, 1);

                roleIdsInput.value = currentIds.join(',');
                roleNamesInput.value = currentNames.join(',');
                displayRoleTags(itemId); // Re-render tags after removal
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            // ... existing code ...
            // Call displayRoleTags for each item after data is loaded
            // This part needs to be called inside the fetch success callback
            
            // 全选/取消全选功能
            document.getElementById('select-all-checkbox').addEventListener('change', function() {
                const isChecked = this.checked;
                document.querySelectorAll('.row-checkbox').forEach(checkbox => {
                    checkbox.checked = isChecked;
                });
                updateBatchActionsVisibility();
            });
            
            // 监听每行复选框的变化
            document.addEventListener('change', function(event) {
                if (event.target.classList.contains('row-checkbox')) {
                    updateBatchActionsVisibility();
                    
                    // 更新全选复选框状态
                    const allCheckboxes = document.querySelectorAll('.row-checkbox');
                    const checkedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
                    document.getElementById('select-all-checkbox').checked = 
                        allCheckboxes.length > 0 && allCheckboxes.length === checkedCheckboxes.length;
                }
            });
        });

        // Prevent default drag over behavior for the entire document to allow drops
        document.addEventListener('dragover', function(event) {
            event.preventDefault();
        });

        document.addEventListener('drop', function(event) {
            event.preventDefault();
        });
        
        // 更新批量操作按钮的显示状态
        function updateBatchActionsVisibility() {
            const checkedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
            const batchActionsDiv = document.querySelector('.batch-actions');
            
            if (checkedCheckboxes.length > 0) {
                batchActionsDiv.style.display = 'block';
            } else {
                batchActionsDiv.style.display = 'none';
            }
        }
        
        // 获取选中的行ID
        function getSelectedIds() {
            const selectedIds = [];
            document.querySelectorAll('.row-checkbox:checked').forEach(checkbox => {
                selectedIds.push(checkbox.dataset.id);
            });
            return selectedIds;
        }
        
      
   
    </script>

    <!-- The Modal -->
    <div id="imageModal" class="modal">
        <!-- Modal content -->
        <div class="modal-content-image">
            <span id="closeImageModal" class="close">&times;</span>
            <img id="modalImage" src="" alt="Enlarged Image">
        </div>
    </div>

<script>
        // Get the modal
        var modal = document.getElementById("imageModal");

        // Get the image and insert it inside the modal - use its "alt" text as a caption
        var modalImg = document.getElementById("modalImage");

        // Get all images within the detail-table


        // Get the <span> element that closes the modal
        var span = document.getElementById("closeImageModal");

        // When the user clicks on <span> (x), close the modal
        span.onclick = function() {
            modal.style.display = "none";
        }

        // When the user clicks anywhere outside of the modal content, close it
        modal.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }

        // Add wheel event listener to the modal image for resizing
        modalImg.addEventListener('wheel', function(event) {
            event.preventDefault(); // Prevent default scroll behavior

            const delta = event.deltaY > 0 ? -10 : 10; // Adjust size by 10px
            let currentWidth = modalImg.offsetWidth;
            let newWidth = currentWidth + delta;

            // Optional: Set minimum and maximum width limits
            const minWidth = 50;
            const maxWidth = window.innerWidth * 0.9; // Max 90% of window width

            if (newWidth < minWidth) {
                newWidth = minWidth;
            } else if (newWidth > maxWidth) {
                newWidth = maxWidth;
            }

            modalImg.style.width = newWidth + 'px';
            modalImg.style.height = 'auto'; // Maintain aspect ratio
        });
</script>
<script>
    function editRole(roleId) {
        window.open(`/public/html/edit_role.html?id=${roleId}`, '_blank');
    }
</script>
</body>
</html>